package org.tis.tools.senior.module.developer.controller;

import com.baomidou.mybatisplus.plugins.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.tis.tools.core.web.controller.BaseController;
import org.tis.tools.core.web.vo.SmartPage;
import org.tis.tools.model.common.ResultVO;
import org.tis.tools.senior.module.core.web.util.ShiroUtil;
import org.tis.tools.senior.module.developer.controller.request.DeliveryProcessRequest;
import org.tis.tools.senior.module.developer.entity.SCheck;
import org.tis.tools.senior.module.developer.entity.SCheckList;
import org.tis.tools.senior.module.developer.entity.SDeliveryList;
import org.tis.tools.senior.module.developer.entity.SSvnAccount;
import org.tis.tools.senior.module.developer.entity.enums.CheckStatus;
import org.tis.tools.senior.module.developer.entity.enums.PatchType;
import org.tis.tools.senior.module.developer.entity.vo.CheckMergeDetail;
import org.tis.tools.senior.module.developer.entity.vo.CheckResultDetail;
import org.tis.tools.senior.module.developer.entity.vo.DeliveryProjectDetail;
import org.tis.tools.senior.module.developer.exception.DeveloperException;
import org.tis.tools.senior.module.developer.service.ISCheckService;
import org.tis.tools.senior.module.developer.service.ISDeliveryListService;
import org.tmatesoft.svn.core.SVNException;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Pattern;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * sCheck的Controller类
 *
 * @author Auto Generate Tools
 * @date 2018/06/27
 */
@RestController
@RequestMapping("/checks")
@Api(value = "核对controller", tags = {"核对操作接口"})
public class SCheckController extends BaseController<SCheck> {

    @Autowired
    private ISCheckService sCheckService;

    @Autowired
    private ISDeliveryListService deliveryListService;

    /**
     * 核对清单
     *
     * @param profileId
     * @param packTiming
     * @return
     */
    //@OperateLog(type = OperateType.ADD, desc = "核对清单")
    @ApiOperation(value = "核对清单", notes = "body传参")
    @RequiresRoles(value = "rct")
    @PostMapping("/profiles/{profileId}/packTiming/{packTiming}")
    public ResultVO check(@PathVariable @NotBlank(message = "环境ID不能为空") String profileId,
                          @PathVariable
                          @Pattern(regexp = "^(20|21|22|23|[0-1]\\d):[0-5]\\d$", message = "打包窗口不能为空或格式错误")
                                  String packTiming) throws SVNException {
        CheckResultDetail detail = sCheckService.check(profileId, packTiming, ShiroUtil.getUser().getUserId());
        return ResultVO.success(detail);
    }

    /**
     * 查看核对详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "查看核对详情", notes = "url传参")
    @GetMapping("/{id}")
    @RequiresRoles(value = "rct")
    public ResultVO detail(@PathVariable @NotBlank(message = "id不能为空") String id) {
        CheckResultDetail detail = sCheckService.detail(id);
        return ResultVO.success("查询成功", detail);
    }

    /**
     * 去合并
     *
     * @return
     */
    @ApiOperation(value = "去合并", notes = "body传参")
    @GetMapping("/profiles/{profileId}/packTiming/{packTiming}")
    @RequiresRoles(value = "rct")
    public ResultVO merge(@PathVariable @NotBlank(message = "环境ID不能为空") String profileId,
                          @PathVariable
                          @Pattern(regexp = "^(20|21|22|23|[0-1]\\d):[0-5]\\d$", message = "打包窗口不能为空或格式错误")
                                  String packTiming) {
        List<CheckMergeDetail> detail = sCheckService.getMergeList(profileId, packTiming);
        return ResultVO.success("查询成功", detail);
    }

    /**
     * 查看核对列表
     *
     * @param page
     * @return
     */
    @ApiOperation(value = "查看核对列表", notes = "body传参")
    @PostMapping("/list")
    @RequiresRoles(value = "rct")
    public ResultVO list(@RequestBody @Validated SmartPage<SCheck> page) {
        return ResultVO.success("查询成功", sCheckService.selectPage(getPage(page), getCondition(page)));
    }

    /**
     * 投放申请结果处理
     *
     * @param request
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "申请结果处理")
    @ApiOperation(value = "投放申请结果处理", notes = "body传参")
    @PutMapping("/delivery/{id}/result")
    @RequiresRoles("rct")
    public ResultVO process(@PathVariable @NotBlank(message = "投放申请ID不能为空！") String id,
                            @RequestBody @Validated DeliveryProcessRequest request) throws SVNException {
        sCheckService.process(id, request.getResult(), request.getDesc(), ShiroUtil.getUser().getUserId());
        return ResultVO.success("处理成功");
    }

    /**
     * 完成核对
     *
     * @param id
     * @param status
     * @return
     */
    //@OperateLog(type = OperateType.UPDATE, desc = "申请完成核对")
    @ApiOperation(value = "完成核对", notes = "url传参")
    @PutMapping("/{id}/status/{status}")
    @RequiresRoles("rct")
    public ResultVO changeCheckStatus(@PathVariable @NotBlank(message = "核对ID不能为空！") String id,
                                      @PathVariable @NotBlank(message = "核对状态不能为空！") String status)
            throws SVNException {
        sCheckService.completeCheck(id, CheckStatus.what(status));
        return ResultVO.success("操作成功！");
    }

    /**
     * Excel导出清单
     *
     * @return
     */
    //@OperateLog(type = OperateType.QUERY, desc = "Excel导出申请清单")
    @ApiOperation(value = "Excel导出申请清单", notes = "url传参")
    @PostMapping("/excel")
    public ResultVO deliveryExportExcel(HttpServletResponse response, @RequestBody @NotEmpty List<Integer> guidDelivery) {

        SSvnAccount user = ShiroUtil.getUser();
        if (user == null) {
            throw new DeveloperException("尚未登录，请登录后再操作！");
        }
        List<SDeliveryList> sDeliveryLists = deliveryListService.selectDeliveryListExcel(guidDelivery);

        OutputStream os = null;
        InputStream is = null;
        try {
            is = this.getClass().getResourceAsStream("/template/excel.xls");
            HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
            HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(0);
            for (int i = 0; i < sDeliveryLists.size(); i++) {
                SDeliveryList sdl = sDeliveryLists.get(i);
                HSSFRow row = hssfSheet.createRow(i + 2);
                row.createCell(0).setCellValue("/" + sdl.getPartOfProject());
                row.createCell(1).setCellValue(sdl.getPatchType());
                row.createCell(2).setCellValue("*." + sdl.getPatchType());
                row.createCell(3).setCellValue(sdl.getDeployWhere());
                if (PatchType.ECD.equals(sdl.getPatchType())) {
                    row.createCell(4).setCellValue("/" + sdl.getFullPath());
                } else {
                    row.createCell(4).setCellValue("/" + sdl.getFullPath().substring(
                                sdl.getFullPath().indexOf(sdl.getPartOfProject())));
                }
                row.createCell(5).setCellValue("all");
                row.createCell(6).setCellValue("all");
                row.createCell(7).setCellValue(user.getUserId());
            }
            String fileName = "清单";
            response.setCharacterEncoding("utf-8");
//            response.addHeader("Content-Type", "application/json;");
            response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO8859-1") + ".xls");
            os = response.getOutputStream();
            hssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            throw new DeveloperException("导出清单异常！");
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                throw new DeveloperException("输出流或输入流为空！");
            }
        }

        return ResultVO.success("导出成功");
    }

    /**
     * 查询核对结果合并清单异常分页
     *
     * @param guidCheck
     * @param page
     * @return
     */
    @ApiOperation(value = "核对结果中合并清单分页接口", notes = "url和body都需要传参")
    @PostMapping("/{guidCheck}/checkList/merge/list")
    public ResultVO checkListInMergeList(@PathVariable @NotBlank(message = "核对ID不能为空！")
                                         @ApiParam(name = "guidCheck", value = "核对的guid", required = true)
                                                 String guidCheck,
                                         @RequestBody @Validated
                                         @ApiParam(name = "page", value = "分页对象", required = true)
                                                 SmartPage<SCheckList> page) {
        Page<SCheckList> list = sCheckService.selectCheckListInMerges(guidCheck, page.getPageObj(), page.getConditionWrapper());
        return ResultVO.success("查询成功", list);
    }

    /**
     * 查询核对结果申请清单异常
     *
     * @param guidCheck
     * @return
     */
    @ApiOperation(value = "核对结果中申请查询接口", notes = "url传参")
    @GetMapping("/{guidCheck}/checkList/delivery/{guidDelivery}/list")
    public ResultVO checkListInDeliveryList(
            @PathVariable
            @NotBlank(message = "核对ID不能为空！")
            @ApiParam(name = "guidCheck", value = "核对的guid", required = true)
                    String guidCheck,
            @PathVariable
            @NotBlank(message = "申请ID不能为空！")
            @ApiParam(name = "guidDelivery", value = "申请的guid", required = true)
                    String guidDelivery) {
        List<DeliveryProjectDetail> list = sCheckService.selectCheckListInDelivery(guidCheck, guidDelivery);
        return ResultVO.success("查询成功", list);
    }

    /**
     * 查询一条清单的导出及部署类型
     * @return
     */
    @ApiOperation(value = "查询一条清单的导出及部署类型", notes = "url传参")
    @GetMapping("/{guidCheckList}/pathPatchDeploy")
    public ResultVO pathPatchDeploy(@PathVariable
                                        @NotBlank(message = "核对ID不能为空！")
                                        @ApiParam(name = "guidCheckList", value = "核对代码的guid", required = true)
                                                String guidCheckList){

        return ResultVO.success("查询成功", sCheckService.selectPathPatchDeploy(guidCheckList));
    }

}

